import { Space, Card, Button, Modal } from 'antd-mobile'
import { TimeBar } from '~/components'
import { useNavigate, createSearchParams } from 'react-router-dom'
import { getReservation } from '~/services/reservationSpace'
import { useRequest, useSessionStorageState } from 'ahooks';
import style from './index.module.css'

function Reservation({ item = {}, spacetype, date }) {
	let navigate = useNavigate();
	const [userInfo = {}] = useSessionStorageState('user');
	const showBtn = item?.timeList?.find(e => e.status === '可预约');
	const spaceDesc = `${ item.deviceinfo }${ item.contains && `|容纳人数${item.contains}人`}`

	const { run: goTo } = useRequest(
		() => getReservation({code: '09',outid: userInfo?.uid, spacetype}),
		{
			manual: true,
			onSuccess: (res) => {
				if (res?.data?.code === '00') {
					const params = {
						date,
						spaceDesc,
						spacetype,
						spaceid: item.id,
						spacename: item.name,
					}
					navigate({
						pathname: '/reservation-page',
						search: `?${createSearchParams(params)}`
					})
				} else {
					Modal.alert({
						title: '预约限制',
						content: res?.data?.msg || '暂时无法预约',
					})
				}
			}
		}
	);
	return (
		<Card className={style.card}>
			<Space block direction='vertical' style={{ '--gap-vertical': '15px', padding: '10px', boxSizing: 'border-box' }}>
				<Space block align='start' justify='between'>
					<Space direction='vertical'>
						<b className={style.roomName}>
							{ item.name }
						</b>
						<span className={style.roomDesc}>
							{ spaceDesc }
						</span>
					</Space>

					{showBtn ? (
						<Button size='small' color='primary' shape='rounded' onClick={goTo}>
							预约
						</Button>
					) : (
						<Button size="small" disabled style={{ '--background-color': '#EFEFEF' }} shape="rounded">
                            已约满
						</Button>
					)}
				</Space>
				<TimeBar timeList={item?.timeList} />
			</Space>
		</Card>
	)
}

export default Reservation
